package com.jiezhuo.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.ParseException;
import org.apache.http.client.CookieStore;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.HashMap;

/**
 * @ClassName HttpClientUtil
 * @Description httpclient get/post方式调用接口
 * @Author simonsfan
 * @Date 2019/1/7
 * Version  1.0
 */
public class HttpClientUtil {
    private static Logger log = LoggerFactory.getLogger(HttpClientUtil.class);

    private static final String ENCODING = "UTF-8";

    private static final int CONNECTION_TIME_OUT = 3000;

    private static final int SO_TIME_OUT = 5000;

    private static final boolean STALE_CHECK_ENABLED = true;

    private static final boolean TCP_NO_DELAY = true;

    private static final int DEFAULT_MAX_CONNECTIONS_PER_HOST = 100;

    private static final int MAX_TOTAL_CONNECTIONS = 1000;

//    private static final HttpConnectionManager connectionManager;

//    public static final HttpClient client;

//    static {
//        HttpConnectionManagerParams params = loadHttpConfFromFile();
//
//        connectionManager = new MultiThreadedHttpConnectionManager();
//
//        connectionManager.setParams(params);
//
//        client = new HttpClient(connectionManager);
//    }

//    private static HttpConnectionManagerParams loadHttpConfFromFile() {
//        HttpConnectionManagerParams params = new HttpConnectionManagerParams();
//        params.setConnectionTimeout(CONNECTION_TIME_OUT);
//        params.setStaleCheckingEnabled(STALE_CHECK_ENABLED);
//        params.setTcpNoDelay(TCP_NO_DELAY);
//        params.setSoTimeout(SO_TIME_OUT);
//        params.setDefaultMaxConnectionsPerHost(DEFAULT_MAX_CONNECTIONS_PER_HOST);
//        params.setMaxTotalConnections(MAX_TOTAL_CONNECTIONS);
//        params.setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(0, false));
//        return params;
//    }

    /**
     * get请求
     *
     * @param url
     * @return
     */
    public static String doGet(String url) throws Exception {
        CloseableHttpClient httpclient = HttpClients.createDefault();
        String result = null;
        HttpGet get = new HttpGet(url);

//        get.addHeader("Content-Type",contentType);
        HttpResponse httpResponse = httpclient.execute(get);
        // 获取结果实体
        HttpEntity entity = httpResponse.getEntity();

        if (entity != null) {
            // 按指定编码转换结果实体为String类型
            result = EntityUtils.toString(entity, HTTP.UTF_8);


        }
        return result;
    }
    public static String doGet(String url,String jsessionid) throws Exception {
//        CookieStore cookieStore = new BasicCookieStor();
        //添加cookie
//        BasicClientCookie cookie = new BasicClientCookie("JSESSIONID", "f08f076d-5490-4a72-b1eb-48b58f7ab84c");
//        //放入cookiestore
//        cookieStore.addCookie(cookie);
//        //声明httpclient，同时添加上cookies
//        CloseableHttpClient httpclient = HttpClients.custom()
//                .setDefaultCookieStore(cookieStore)//设置Cookie
//                .build();


        CloseableHttpClient httpclient = HttpClients.createDefault();
        String result = null;
        HttpGet get = new HttpGet(url);
        get.addHeader("Cookie","token=BGaDeOdIR1");
        HttpResponse httpResponse = httpclient.execute(get);
        // 获取结果实体
        HttpEntity entity = httpResponse.getEntity();
        if (entity != null) {
            // 按指定编码转换结果实体为String类型
            result = EntityUtils.toString(entity, HTTP.UTF_8);
        }
        return result;
    }


//    public static void main(String[] args) {
//        String str="11 03 00 01 00 01 D7 5A";
//        String s = str.replace(" ", "").toString();
//        System.out.println(s);
//    }

    public static String doPost(String url, String contentType, String content) throws Exception {
        CloseableHttpClient httpclient = HttpClients.createDefault();
        HttpPost post = new HttpPost(url);
        post.setEntity(new StringEntity(content.toString(),"UTF-8"));
        post.addHeader("Connection", "Keep-Alive");
        post.addHeader("Content-Type",contentType);
        HttpResponse httpResponse = httpclient.execute(post);
        // 获取结果实体
        HttpEntity entity = httpResponse.getEntity();
        String string="";
        JSONObject jsonObject=null;
        if (entity != null) {
            // 按指定编码转换结果实体为String类型
             string = EntityUtils.toString(entity, HTTP.UTF_8);
        }
       return string;
    }


    public static String doPost(String url,  HashMap<String,String> map) throws Exception {
        CloseableHttpClient httpclient = HttpClients.createDefault();
        JSONObject jsonObject = new JSONObject();
        for(HashMap.Entry entry:map.entrySet()){
            jsonObject.put(entry.getKey().toString(),entry.getValue().toString());
        }   // 以上循环操作是将 Map对象转化成 JsonObject对象
////        System.out.println(jsonObject.toString());
        StringEntity entity = new StringEntity(jsonObject.toString(), Consts.UTF_8);
        HttpPost httppost = new HttpPost(url);
        httppost.setEntity(entity);     //设置请求体
        CloseableHttpResponse response = null;
        try {
            response = httpclient.execute(httppost);
        } catch (IndexOutOfBoundsException e) {
            e.printStackTrace();
        }
        HttpEntity entity1 = response.getEntity();
        String result = null;
        try {
            result = EntityUtils.toString(entity1);
        } catch (ParseException | IOException e) {
            e.printStackTrace();
        }

        return result;
    }
}

